<?php
namespace app\manage\controller;

class SystemPrivilegeNew extends Base
{
    public function index(){
        if(request()->isAjax()){
            $page = input('page');
            $limit = input('limit');
            $id = input('id');
            $url = input('interface');

            $where = [];
            !empty($id) && $where['id'] = $id;
            !empty($url) && $where['url'] = ['like', '%'.$url.'%'];

            if( ! $count=model('SystemPrivilegeNew')->where($where)->count() ){
                $this->layTable();
            }

            $data = model('SystemPrivilegeNew')
                ->where($where)
                ->limit(($page-1)*$limit, $limit)
                ->order('id desc')
                ->select();

            $this->layTable(0, '', $data, $count);
        }else{
            return view();
        }
    }

    public function add(){
        if( request()->isAjax() ){
            $data = input();

            //权限
            $data1['pri_name'] = $data['pri_name'];
            $data1['url'] = $data['url'];
            $data1['pid'] = $data['pri_id'];
            !empty($data['rid']) && $data1['rid'] = 1;
            $addPriRs = model('SystemPrivilegeNew')->save( $data1 );

            //菜单
            if(!empty($data['is_menu'])){
                $data2['title'] = $data['pri_name'];
                $data2['url'] = $data['url'];
                $data2['pid'] = $data['menu_id'];
                $data2['pri_id'] = model('SystemPrivilegeNew')->id;
                $addMenuRs = model('SystemMenuNew')->save( $data2 );
            }

            $addPriRs ? $this->layJson(0, '添加成功') : $this->layJson(1, '添加失败，请重试');
        }else{
            $select = model('SystemMenuNew')->where('status', 1)->select();
            import('cate.Category');
            $menuList = \Category::unlimitedForLevel($select);
            return view('', ['menu_list'=>$menuList]);
        }
    }

    public function edit(){
        if( request()->isAjax() ){
            $data1 = input();
            $editRs1 = model('SystemPrivilegeNew')->isUpdate(true)->save( $data1 );

            $data2['title'] = $data1['pri_name'];
            $data2['url'] = $data1['url'];
            $editRs2 = model('SystemMenuNew')->isUpdate(true)->save( $data2, ['pri_id'=>input('id')] );

            $editRs1!==false ? $this->layJson(0, '编辑成功') : $this->layJson(1, model('SystemPrivilegeNew')->getError());
        }else{
            $find = model('SystemPrivilegeNew')->where('id', input('id'))->find();
            $select = model('SystemPrivilegeNew')->select();
            import('cate.Category');
            $priList = \Category::unlimitedForLevel($select);
            return view('', ['find'=>$find, 'pri_list'=>$priList]);
        }
    }

    public function del(){
        model('SystemPrivilegeNew')->destroy(input('id')) ? $this->layJson(0, '删除成功') : $this->layJson(1, '删除失败，请重试');
    }
}